package com.mryin.shiro;

import org.apache.shiro.web.servlet.Cookie;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.UUID;

/**
 * @author: Mr.Yin
 * @create: 2021-02-27 21:15
    解决 session 共享问题
 * 让前端拿到该token
 * 严格是说  shiro+redis 的session共享问题
 */
@Configuration
public class TokenWebSessionManager extends DefaultWebSessionManager {
    private static final String AUTHORIZATION = "TOKEN";
    private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";

    public TokenWebSessionManager(){
        super();
    }
    /**
     * 重写getSessionId方法
     * 这里主要是进行判断 请求当中有没有Token
     * 没有则立马生成一个给到出去
     * 有则在请求头当中拿
     *
     * @param request
     * @param response
     * @return
     */
    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        System.out.println("获取当前请求地址:" + httpServletRequest.getRequestURI());
        String header = WebUtils.toHttp(request).getHeader(AUTHORIZATION);
        if(!StringUtils.isEmpty(header)){
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,REFERENCED_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID,header);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID,Boolean.TRUE);
            System.out.println(header);
            return header;
        }else{
            Serializable sessionId = super.getSessionId(request, response);
            System.out.println(sessionId);
            return sessionId;
        }
    }
}